package managedbean.staff;

import entity.UserAccessRightsEntity;
import exception.ExistException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import managedbean.PageRedirectorBean;
import org.primefaces.model.MenuModel;
import session.stateless.SystemMessagesBean;
import session.stateless.StaffAccountSessionBean;
import util.entityhelper.StaffAccountState;
import util.enumhelper.SupportedLocale;
import util.enumeration.Country;
import util.enumeration.Department;
import util.enumeration.Gender;
import util.enumeration.JobPosition;
import util.generator.StaffMenuGenerator;
import util.localization.WebLocalization;

/**
 *
 * @author Swee Zhi
 */
@ManagedBean
@RequestScoped
public class StaffDeleteAccountManagedBean implements Serializable {
    @EJB
    private StaffAccountSessionBean staffAccountMgr;
    // EXCEPTION
    @EJB
    private SystemMessagesBean systemMessages;
    
    // fields for this bean
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private WebLocalization localization;
    private PageRedirectorBean redirect;
    
    // use entity helpers to extract data (attribute extraction and formatting instead of entity in this open bean)
    private StaffAccountState staffAcctState;
    
    // fields passed from session
    private Long staffAccountId;
    private String preferredLocale;
    private String statusMessageFromEdit;
    
    // other fields from database to be displayed
    private String username;
    private String currentPassword;
    private String lastname;
    private String firstname;
    private String gender;
    private String birthdate;
    private String country;
    private String locale;
    private String email;
    private String emailSecondary;
    private String department;
    private String jobPosition;
    private String joinDate;
    private List<String> accessRightsList;
   
    private String name;
    private String language;
    private Date passwordChangeDate;
    private MenuModel staffMenuModel;
    private StaffAccountState accountSelected;
    private String accountUsername;
    
    
    public StaffDeleteAccountManagedBean() {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        
        redirect = new PageRedirectorBean();
        /* pre-load values from session and database */
        // get account ID values from session
        if (ctx.getExternalContext().getSessionMap().containsKey("staffAccountId")) {
            // get session values
            staffAccountId = (Long) ctx.getExternalContext().getSessionMap().get("staffAccountId");
            // put back session values
            ctx.getExternalContext().getSessionMap().put("staffAccountId", staffAccountId);
            if (ctx.getExternalContext().getSessionMap().containsKey("statusMessageFromEdit")) {
                statusMessageFromEdit = (String) ctx.getExternalContext().getSessionMap().get("statusMessageFromEdit");
            }
        }
        else {
            // redirect back to login
            redirect.goStaffLoginPageAtPreviousLevel();
        }
        /* END load values from session and database */    
    }
    
    public void initView(PhaseEvent event) {
        try {
//            // set language for all MANAGERS for all THROWABLE EXCEPTIONS in backend
//            // to use this line everytime possible language changes
            staffAccountMgr.setSelectedLocale(preferredLocale);
//            // get data from backend, exception alrd thrown by backend if these methods fail.
//            
            staffAcctState = staffAccountMgr.getStaffAccountByID(staffAccountId);
            
            // menu
            StaffMenuGenerator menuGenerator = new StaffMenuGenerator(staffAcctState);
            staffMenuModel = menuGenerator.generateStaffMenu();
        }
//        catch (ExistException ex) {
////            System.out.println(ex.getMessage());
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
//        }
        catch (Exception ex) {
            ex.printStackTrace();
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
    }
    
    public void selectAccount(ActionEvent event)
    {
        try {
            // set language for all MANAGERS for all THROWABLE EXCEPTIONS in backend
            // to use this line everytime possible language changes
            staffAccountMgr.setSelectedLocale(preferredLocale);
            // get data from backend, exception alrd thrown by backend if these methods fail.
            
            for (int i = 0; i < staffAccountMgr.getStaffAccounts().size(); i++) {
                if (staffAccountMgr.getStaffAccountByUsername(accountUsername).getUsername().equals(accountUsername)) {
                    accountSelected = staffAccountMgr.getStaffAccountByUsername(accountUsername);
                }
            }
        }
        catch (ExistException ex) {
            String statusMessage = systemMessages.getSystemMessage("STAFF_ACCT_DOES_NOT_EXIST", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
        }
        
        try {
            staffAcctState = accountSelected;
            System.out.println("staffAcctState: " + staffAcctState.getId());

          
            
                System.out.println("other: ");
                username = staffAcctState.getUsername();
                currentPassword = staffAcctState.getPassword();

                lastname = staffAcctState.getStaff().getLastName();
                firstname = staffAcctState.getStaff().getFirstName();
                name = lastname + " " + firstname;

                Gender savedGender = staffAcctState.getStaff().getGender();
                gender = localization.getLocalizedGender(savedGender);

                Date savedBirthdate = staffAcctState.getStaff().getBirthdate();
                birthdate = localization.getLocalizedDateFormat(savedBirthdate);

                Country savedCountry = staffAcctState.getStaff().getCountry();
                country = localization.getLocalizedCountry(savedCountry).toString();

                String savedLocale = staffAcctState.getStaff().getLocale();
                language = localization.getLocalizedLanguage(SupportedLocale.getLanguageBySupportedLocaleString(savedLocale));

                email = staffAcctState.getStaff().getEmail();

                if (staffAcctState.getStaff().getEmailSecondary().isEmpty()) {
                    emailSecondary = "-";
                }
                else {
                    emailSecondary = staffAcctState.getStaff().getEmailSecondary();
                }

                Department savedDepartment = staffAcctState.getStaff().getDepartment();
                department = localization.getLocalizedDepartment(savedDepartment);

                JobPosition savedJobPosition = staffAcctState.getStaff().getJobPosition();
                jobPosition = localization.getLocalizedJobPosition(savedJobPosition);

                Date savedJoinDate = staffAcctState.getStaff().getJoinDate();
                joinDate = localization.getLocalizedDateFormat(savedJoinDate);

                passwordChangeDate = staffAcctState.getPasswordChangeDate();

                List<UserAccessRightsEntity> savedList = new ArrayList();
                savedList = staffAcctState.getAccessRights();
                accessRightsList = new ArrayList();
                // convert from entity to enum
                for (int i=0; i < savedList.size(); i++) {
                    String localizedAccessRight = localization.getLocalizedAccessRight(savedList.get(i).getAccessRight());
                    accessRightsList.add(localizedAccessRight);
                }

                /* PRE-SET MENU BASED ON ACCESS RIGHTS */
                // moved to util.generator StaffMenuGenerator
                StaffMenuGenerator menuGenerator = new StaffMenuGenerator(staffAcctState);
                staffMenuModel = menuGenerator.generateStaffMenu();
                /* END PRE-SET MENU BASED ON ACCESS RIGHTS */ 
        }
//        catch (ExistException ex) {
////            System.out.println(ex.getMessage());
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
//        }
        catch (Exception ex) {
            System.out.println(ex.getMessage());
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
    }
    
    public void deleteStaff(ActionEvent event) {
        try {
            staffAccountMgr.deleteStaffAccount(accountSelected.getId());
            String statusMessage = systemMessages.getSystemMessage("STAFF_ACCT_DELETED", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));
        }
        catch (ExistException ex) {
//            System.out.println(ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
    }

    public StaffAccountSessionBean getStaffAccountMgr() {
        return staffAccountMgr;
    }

    public void setStaffAccountMgr(StaffAccountSessionBean staffAccountMgr) {
        this.staffAccountMgr = staffAccountMgr;
    }

    public String getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }

    public FacesContext getCtx() {
        return ctx;
    }

    public void setCtx(FacesContext ctx) {
        this.ctx = ctx;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getLocale() {
        return locale;
    }

    public void setLocale(String locale) {
        this.locale = locale;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPreferredLocale() {
        return preferredLocale;
    }

    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmailSecondary() {
        return emailSecondary;
    }

    public void setEmailSecondary(String emailSecondary) {
        this.emailSecondary = emailSecondary;
    }

    public Long getStaffAccountId() {
        return staffAccountId;
    }

    public void setStaffAccountId(Long staffAccountId) {
        this.staffAccountId = staffAccountId;
    }

    public StaffAccountState getStaffAcctState() {
        return staffAcctState;
    }

    public void setStaffAcctState(StaffAccountState staffAcctState) {
        this.staffAcctState = staffAcctState;
    }

    public String getCurrentPassword() {
        return currentPassword;
    }

    public void setCurrentPassword(String currentPassword) {
        this.currentPassword = currentPassword;
    }

    public WebLocalization getLocalization() {
        return localization;
    }

    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public List<String> getAccessRightsList() {
        return accessRightsList;
    }

    public void setAccessRightsList(List<String> accessRightsList) {
        this.accessRightsList = accessRightsList;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getJobPosition() {
        return jobPosition;
    }

    public void setJobPosition(String jobPosition) {
        this.jobPosition = jobPosition;
    }

    public String getJoinDate() {
        return joinDate;
    }

    public void setJoinDate(String joinDate) {
        this.joinDate = joinDate;
    }

    public Date getPasswordChangeDate() {
        return passwordChangeDate;
    }

    public void setPasswordChangeDate(Date passwordChangeDate) {
        this.passwordChangeDate = passwordChangeDate;
    }

    public MenuModel getStaffMenuModel() {
        return staffMenuModel;
    }

    public void setStaffMenuModel(MenuModel staffMenuModel) {
        this.staffMenuModel = staffMenuModel;
    }

    public PageRedirectorBean getRedirect() {
        return redirect;
    }

    public void setRedirect(PageRedirectorBean redirect) {
        this.redirect = redirect;
    }

    public String getStatusMessageFromEdit() {
        return statusMessageFromEdit;
    }

    public void setStatusMessageFromEdit(String statusMessageFromEdit) {
        this.statusMessageFromEdit = statusMessageFromEdit;
    }

    public StaffAccountState getAccountSelected() {
        return accountSelected;
    }

    public void setAccountSelected(StaffAccountState accountSelected) {
        this.accountSelected = accountSelected;
    }

    public String getAccountUsername() {
        return accountUsername;
    }

    public void setAccountUsername(String accountUsername) {
        this.accountUsername = accountUsername;
    }
    
}
